<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(3)
        var c = new Node(2)
        var d = new Node(3)
        var e = new Node(4)
        var f = new Node(5)
        var g = new Node(5)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g
        /* 
        1 时间O(n) n为节点个数 
          空间为O(n) 是栈数组空间的使用 最坏是每个节点都走了一遍
        */
        var hasPathSum = function (root, targetSum) {
            // 判空
            if (!root) return false
            let valArr = [0] // 值数组
            let nodeArr = [root] // 节点数组

            while (nodeArr.length > 0) {
                debugger
                let count = valArr.shift()
                let curNode = nodeArr.shift()
                
                count += curNode.val

                // 叶子节点 找到目标值
                if (!curNode.left && !curNode.right && count === targetSum) {
                    return true
                }

                // 判断左节点和右节点是否有值
                if (curNode.left) {
                    nodeArr.push(curNode.left)
                    valArr.push(count)
                }

                if (curNode.right) {
                    nodeArr.push(curNode.right)
                    valArr.push(count)
                }
            }

            return false
        }
        console.log(hasPathSum(a, 8));

    </script>
</body>

</html>